import React, { useState } from 'react'
import './Login.scss'
import { Form, message, Input } from 'antd'
import { adminLoginApi } from '@/api';
import { useSelector, useDispatch } from 'react-redux';
import { setToken,removeToken } from '@/store/token';
import { useNavigate } from "react-router-dom"

const login:React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const state:Store.tokenRes = useSelector((state:any) => state.token);
  console.log(state);
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [data,setData] = useState({
    username:"",
    password:""
  })
  const onFinish = () => {
    try {
      form.validateFields().then(async(ress)=>{
        const res =  await adminLoginApi({password:data.password,username:data.username})
        if (res.code !== 200) {
          messageApi.open({
            type: 'error',
            content: res.error,
          });
        } else {
          dispatch(setToken({
            token:res.data.token,
            avatar:res.data.avatar,
            user:res.username
          }))
          localStorage.setItem('token',res.data.token);
          messageApi.open({
            type: 'success',
            content: "登录成功!",
          });
          navigate("/home")
        }
      }).catch(error=>{
        // console.log(error);
      })
    } catch (error) {
      messageApi.open({
        type: 'error',
        content: error as string,
      });
    }
  };

  return (
    <div className="container">
      {contextHolder}
      <div className="login">
        <h2>登陆\注册</h2>
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          autoComplete="off"
        >
          <Form.Item
            label="用户名:"
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input value={data.username} onChange={(e) => {setData({...data,username:e.target.value})}}/>
          </Form.Item>

          <Form.Item
            label="密码:"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password value={data.password} onChange={(e) => {setData({...data,password:e.target.value})}}/>
          </Form.Item>
        </Form>
        <div className="btn">
          <button className="login_btn" onClick={() => onFinish()} >登 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录</button>
        </div>
        <a
        // href="/register"
        onClick={()=>{
          dispatch(removeToken())
        }} style={{ display: 'block',color: 'white', textDecoration: 'none', textAlign: 'center',width: '100%' }}>注册新用户</a>
      </div>
    </div>
  )
}
export default login;
